package com.nbcio.demo.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.nbcio.demo.domain.DeepSeekRequest;
import com.nbcio.demo.service.IDeepSeekService;
import com.nbcio.demo.utils.HttpClientSingleton;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import okio.BufferedSource;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;

@Service
@RequiredArgsConstructor
public class DeepSeekServiceImpl implements IDeepSeekService {
	@Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    public String callDeepSeekAPI(DeepSeekRequest request) throws IOException {
    	OkHttpClient client = HttpClientSingleton.getClient();
        
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, new Gson().toJson(request));
        
        Request httpRequest = new Request.Builder()
                .url(apiUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
    			.addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }
    
    //支持流式响应
    public void callDeepSeekStreamAPI(DeepSeekRequest request, HttpServletResponse servletResponse) throws IOException {
        OkHttpClient client = HttpClientSingleton.getClient();

        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, new Gson().toJson(request));

        Request httpRequest = new Request.Builder()
                .url(apiUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            OutputStream outputStream = servletResponse.getOutputStream();
            try (BufferedSource source = response.body().source()) {
                while (!source.exhausted()) {
                    String chunk = source.readUtf8Line();
                    if (chunk != null) {
                        outputStream.write((chunk + "\n").getBytes(StandardCharsets.UTF_8));
                        outputStream.flush();
                    }
                }
            }
        }
    }
    
    public void callDeepSeekAPI(DeepSeekRequest request, OutputStream outputStream) throws IOException {
        OkHttpClient client = HttpClientSingleton.getClient();

        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, new Gson().toJson(request));

        Request httpRequest = new Request.Builder()
                .url(apiUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 逐行读取响应内容并写入 OutputStream
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    outputStream.write(line.getBytes(StandardCharsets.UTF_8));
                    outputStream.write("\n".getBytes(StandardCharsets.UTF_8)); // 换行
                    outputStream.flush(); // 确保内容实时发送
                }
            }
        }
    }
    
}
